rm(list=ls())

load("TSCS_data.RData")
api_data <- read.csv("api_data.csv")

# Figure B.1

panel %>% as.data.frame() %>%
  select(country_name,year,polarization) %>%
  mutate(country_name = as.character(country_name),
         year = as.integer(sub("^([0-9]+)$", "\\1", year))) %>%
  left_join(api_data, by = c("country_name","year")) %>%
  drop_na(API,polarization) ->
  ap_data

pearsons_r <- cor(ap_data$API,ap_data$polarization)

pdf(file = "fig_b1.pdf",width = 7,height = 5)

ggplot(ap_data, aes(y = polarization, x = API)) +
  geom_point() +
  geom_smooth(method = "gam") +
  xlab("Affective Polarization Index") +
  ylab("V-Dem Polarization Index") +
  annotate("text", label = paste("Pearson's r:", round(pearsons_r, 3)),
           x = min(ap_data$API), y = max(ap_data$polarization), vjust = 1, hjust = -0.1)

dev.off()
